# -*- coding: utf-8 -*-
# @Author    :breeze
# @Time      :2019/4/10
# @File      : IC16_Past2YearsLoanCardQuasiAccOvduMons.py
# @Email     :wangbaoshan@bbdservice.com

'''eof
name:过去两年贷款和(准)贷记卡最长单笔(非连续)累计逾期次数
code:IC16_Past2YearsLoanCardQuasiAccOvduMons_2D
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime
import pandas as pd

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def intCheck(str):
    try:
        int(str)
        return True
    except:
        return False

def checkNull(data, accountType):
    '''若最近24个月还款状态信息为空，返回结果为缺失值，则进行以下逻辑判断：
1.基本信息段（PD01A）-账户类型（PD01AD01）为D1，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年或账户状态（PD01BD01）为5（转出）且转出月份（PD01BR04）＞5年，则Factor=1,否则Factor=缺失值；
2.基本信息段（PD01A）-账户类型（PD01AD01）为R1,R4，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年，则Factor=1,否则Factor=缺失值；
3.基本信息段（PD01A）-账户类型（PD01AD01）为R2，R3，若最新表现信息段（PD01B）-账户状态（PD01BD01）为4(销户)且关闭日期（PD01BR01）＞5年或账户状态（PD01BD01）为6(未激活)，则Factor=1,否则Factor=缺失值；'''
    if data in null_type_list or data == [{}] or data == 0:
        return 0
    # 账户状态
    PD01BD01 = data[0].get("PD01BD01")
    # 关闭日期
    PD01BR01 = data[0].get("PD01BR01")
    PD01BR01 = dateFormat(PD01BR01)
    # 转出月份
    PD01BR04 = data[0].get("PD01BR04")
    PD01BR04 = dateFormat(PD01BR04)
    fiveYearsAgo = (datetime.datetime.strptime(getNow(), '%Y-%m-%d') - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m")
    if accountType == "D1":
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo) \
                or (PD01BD01 == "5" and PD01BR04 is not None and PD01BR04.strftime("%Y%m") <= fiveYearsAgo):
            return 1
        else:
            return 0
    elif accountType in ["R1", "R4"]:
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo):
            return 1
        else:
            return 0
    elif accountType in ["R2", "R3"]:
        if (PD01BD01 == "4" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo) \
                or (PD01BD01 == "6"):
            return 1
        else:
            return 0
    else:
        return 0

def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

def getCount(statusList, min, max):
    if statusList in null_type_list:
        return -1
    result = []
    flag = False
    for i in statusList:
        try:
            PD01DD01 = i.get("PD01DD01")
            PD01DR03 = i.get("PD01DR03")
            if PD01DD01 not in null_type_list and PD01DR03 not in null_type_list:
                flag = True
            if intCheck(PD01DD01) and min <= int(PD01DD01) <= max or PD01DD01 == 'B':
                result.append(PD01DR03)
        except:
            continue
    if flag:
        return len(set(result))
    else:
        return -1

def getFiveYearsOvduCount(statusList, min, max, endMonth=None):
    if statusList in null_type_list:
        return -1
    if endMonth is None:
        # 使用当前时间为阈值
        endMonthStr = datetime.datetime.now().strftime("%Y-%m-%d")
        endMonth = float(endMonthStr[:4]) * 12 + float(endMonthStr[5:7])
    else:
        try:
            # 使用传入的截止日期计算阈值
            endMonth = float(endMonth[:4]) * 12 + float(endMonth[5:7]) if len(endMonth) >= 6 else None
            if endMonth is None:
                return -1
        except:
            return -1
    month24Ago = endMonth - 24
    result = []
    flag = False
    for i in statusList:
        try:
            PD01ER03 = i.get('PD01ER03')
            PD01ED01 = i.get('PD01ED01')
            PD01ER03 = float(PD01ER03[:4]) *12 + float(PD01ER03[5:7]) if len(PD01ER03) >= 6 else None
            if PD01ER03 not in null_type_list and PD01ED01 not in null_type_list:
                flag = True
            if month24Ago < PD01ER03 <= endMonth and \
                    ((intCheck(PD01ED01) and min <= int(PD01ED01) <= max) or PD01ED01 == 'B'):
                result.append(PD01ER03)
        except:
            continue
    if flag:
        return len(set(result))
    else:
        return -1


def past2YearsLoanCardQuasiAccOvduMons():
    data = IC_DSJ_2D.get('data')
    # 借贷账户信息 PDA[1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            factor = []
            for i in PD01:
                try:
                    # 基本信息段 PD01A[1.1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}]:
                        factor.append(None)
                    elif PD01A == 0:
                        factor.append(0)
                    else:
                        # 账号类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        if PD01AD01 not in null_type_list:
                            if PD01AD01 == "D1" or PD01AD01 == "R1" or PD01AD01 == "R2" or PD01AD01 == "R4":
                                # 最近24个月还款状态信息段 PD01D[0.1]
                                PD01D = getTable(i, 'PD01D', 0, 1)
                                if not (PD01D == [{}] or PD01D == 0):
                                    PD01D = PD01D[0]
                                    # 获取24位状态码列表
                                    PD01DH = PD01D.get("PD01DH")
                                    count = getCount(PD01DH, 1, 7)
                                    if count == -1:
                                        factor.append(None)
                                    else:
                                        factor.append(count)
                                else:
                                    # 最新表现信息段  PD01B  [1..1]
                                    PD01B = getTable(i, 'PD01B', 1, 1)
                                    # 最近5年内的历史表现信息段
                                    PD01E = getTable(i, 'PD01E', 0, 1)
                                    if PD01E == [{}] or PD01B == [{}]:
                                        factor.append(None)
                                    elif PD01E == 0:
                                        factor.append(0)
                                    else:
                                        # 截止年月：
                                        PD01ER02 = PD01E[0].get('PD01ER02')
                                        # 历史表现信息 PD01EH
                                        PD01EH = PD01E[0].get('PD01EH')
                                        # 账户状态
                                        PD01BD01 = PD01B[0].get('PD01BD01')
                                        if PD01BD01 in null_type_list:
                                            factor.append(None)
                                        else:
                                            if PD01BD01 in ['1', '2']:
                                                # 未结清使用截止日期判断
                                                count = getFiveYearsOvduCount(PD01EH, min=1, max=7, endMonth=PD01ER02)
                                            else:
                                                # 已结清使用当前时间判断
                                                count = getFiveYearsOvduCount(PD01EH, min=1, max=7, endMonth=None)
                                            if count == -1:
                                                checkRes = checkNull(PD01B, PD01AD01)
                                                if checkRes:
                                                    factor.append(0)
                                                else:
                                                    factor.append("None")
                                            else:
                                                factor.append(count)

                            elif PD01AD01 == "R3":
                                # 最近24个月还款状态信息段 PD01D[0.1]
                                PD01D = getTable(i, 'PD01D', 0, 1)
                                if not (PD01D == [{}] or PD01D == 0):
                                    PD01D = PD01D[0]
                                    # 获取24位状态码列表
                                    PD01DH = PD01D.get("PD01DH")
                                    count = getCount(PD01DH, 3, 7)
                                    if count == -1:
                                        factor.append(None)
                                    else:
                                        factor.append(count)
                                else:
                                    # 最新表现信息段  PD01B  [1..1]
                                    PD01B = getTable(i, 'PD01B', 1, 1)
                                    # 最近 5 年内的历史表现信息段
                                    PD01E = getTable(i, 'PD01E', 0, 1)
                                    if PD01E == [{}] or PD01B == [{}]:
                                        factor.append(None)
                                    elif PD01E == 0 or PD01B == 0:
                                        factor.append(0)
                                    else:
                                        # 截止年月：
                                        PD01ER02 = PD01E[0].get('PD01ER02')
                                        # 历史表现信息 PD01EH
                                        PD01EH = PD01E[0].get('PD01EH')
                                        # 账户状态
                                        PD01BD01 = PD01B[0].get('PD01BD01')
                                        if PD01BD01 in null_type_list:
                                            factor.append(None)
                                        else:
                                            if PD01BD01 in ['1', '2']:
                                                # 未结清使用截止日期判断
                                                count = getFiveYearsOvduCount(PD01EH, min=3, max=7, endMonth=PD01ER02)
                                            else:
                                                # 已结清使用当前时间判断
                                                count = getFiveYearsOvduCount(PD01EH, min=3, max=7, endMonth=None)
                                            if count == -1:
                                                checkRes = checkNull(PD01B, PD01AD01)
                                                if checkRes:
                                                    factor.append(0)
                                                else:
                                                    factor.append("None")
                                            else:
                                                factor.append(count)
                            else:
                                factor.append(0)
                        else:
                            factor.append(None)
                except:
                    factor.append(None)
                    continue
    if "None" in factor:
        return u"缺失值"
    factor = [x for x in factor if x is not None]
    if len(factor) == 0:
        return u'缺失值'
    else:
        return max(factor)

def getNow():
    data = IC_DSJ_2D.get('data')
    # PRH 报告头 [1..1]
    PRH = getTable(data, 'PRH', 1, 1)
    if PRH == [{}]:
        return u'缺失值'
    elif PRH == 0:
        return 0
    else:
        #报告头信息单元 PA01
        PA01 = getTable(PRH[0], 'PA01', 1, 1)
        if PA01 == [{}]:
            return u'缺失值'
        elif PA01 == 0:
            return 0
        else:
            #报告表示信息段 PA01A [1..1]
            PA01A = getTable(PA01[0], 'PA01A', 1, 1)
            if PA01A == [{}]:
                return u'缺失值'
            elif PA01A == 0:
                return 0
            else:
                #报告时间 PA01AR01
                PA01AR01 = PA01A[0].get('PA01AR01', '')
    if dateFormat(PA01AR01.split('T')[0]):
        return PA01AR01.split('T')[0]
    else:
        return datetime.datetime.now().strftime("%Y-%m-%d")


# 仅使用5年逾期记录计算
def past2YearsLoanCardQuasiAccOvduMons2():
    data = IC_DSJ_2D.get('data')
    # 借贷账户信息 PDA[1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            factor = []
            for i in PD01:
                try:
                    # 基本信息段 PD01A[1.1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}]:
                        factor.append(None)
                    elif PD01A == 0:
                        factor.append(0)
                    else:
                        # 账号类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        if PD01AD01 not in null_type_list:
                            if PD01AD01 == "D1" or PD01AD01 == "R1" or PD01AD01 == "R2" or PD01AD01 == "R4":
                                # 最新表现信息段  PD01B  [1..1]
                                PD01B = getTable(i, 'PD01B', 1, 1)
                                # 最近5年内的历史表现信息段
                                PD01E = getTable(i, 'PD01E', 0, 1)
                                if PD01E == [{}] or PD01B == [{}]:
                                    factor.append(None)
                                elif PD01E == 0:
                                    factor.append(0)
                                else:
                                    # 截止年月：
                                    PD01ER02 = PD01E[0].get('PD01ER02')
                                    # 历史表现信息 PD01EH
                                    PD01EH = PD01E[0].get('PD01EH')
                                    # 账户状态
                                    PD01BD01 = PD01B[0].get('PD01BD01')
                                    if PD01BD01 in null_type_list:
                                        factor.append(None)
                                    else:
                                        if PD01BD01 in ['1', '2']:
                                            # 未结清使用截止日期判断
                                            count = getFiveYearsOvduCount(PD01EH, min=1, max=7, endMonth=PD01ER02)
                                        else:
                                            # 已结清使用当前时间判断
                                            count = getFiveYearsOvduCount(PD01EH, min=1, max=7, endMonth=getNow())
                                        if count == -1:
                                            checkRes = checkNull(PD01B, PD01AD01)
                                            if checkRes:
                                                factor.append(0)
                                            else:
                                                factor.append("None")
                                        else:
                                            factor.append(count)

                            elif PD01AD01 == "R3":
                                # 最新表现信息段  PD01B  [1..1]
                                PD01B = getTable(i, 'PD01B', 1, 1)
                                # 最近 5 年内的历史表现信息段
                                PD01E = getTable(i, 'PD01E', 0, 1)
                                if PD01E == [{}] or PD01B == [{}]:
                                    factor.append(None)
                                elif PD01E == 0 or PD01B == 0:
                                    factor.append(0)
                                else:
                                    # 截止年月：
                                    PD01ER02 = PD01E[0].get('PD01ER02')
                                    # 历史表现信息 PD01EH
                                    PD01EH = PD01E[0].get('PD01EH')
                                    # 账户状态
                                    PD01BD01 = PD01B[0].get('PD01BD01')
                                    if PD01BD01 in null_type_list:
                                        factor.append(None)
                                    else:
                                        if PD01BD01 in ['1', '2']:
                                            # 未结清使用截止日期判断
                                            count = getFiveYearsOvduCount(PD01EH, min=3, max=7, endMonth=PD01ER02)
                                        else:
                                            # 已结清使用当前时间判断
                                            count = getFiveYearsOvduCount(PD01EH, min=3, max=7, endMonth=getNow())
                                        if count == -1:
                                            checkRes = checkNull(PD01B, PD01AD01)
                                            if checkRes:
                                                factor.append(0)
                                            else:
                                                factor.append("None")
                                        else:
                                            factor.append(count)
                            else:
                                factor.append(0)
                        else:
                            factor.append(None)
                except:
                    factor.append(None)
                    continue
    if "None" in factor:
        return u'缺失值'
    factor = [x for x in factor if x is not None]
    if len(factor) == 0:
        return u'缺失值'
    else:
        return max(factor)

# if __name__ == "__main__":
#     import json
#     with open('C:/Users/zdr/Desktop/samples/IC_DSJ_2D.json') as ff:
#         IC_DSJ_2D = json.loads(ff.read())
#     res = past2YearsLoanCardQuasiAccOvduMons2()
#     print(res)

result = past2YearsLoanCardQuasiAccOvduMons2()

